package com.lixin.juc.unsafe;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

public class MainApplication {
    public static void main(String[] args) {
       //testList();
        testSet();
        //testMap();
    }

    public static void testList() {
        //List<String> list = new ArrayList<>(); // 线程不安全
        //List<String> list = new Vector<>(); // 线程安全，但效率低
        //List<String> list = Collections.synchronizedList(new ArrayList<>()); // 线程安全，但效率低
        List<String> list = new CopyOnWriteArrayList<>(); // 线程安全，效率高
        for (int i = 1; i <= 40; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 6));
                System.out.println(list);
            }, String.valueOf(i)).start();
        }
    }

    public static void testSet() {
        //Set<String> set = new HashSet<>(); // 线程不安全
        //Set<String> set = Collections.synchronizedSet(new HashSet<>()); // 线程安全，但效率低
        Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 1; i <= 40; i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0, 6));
                System.out.println(set);
            }, String.valueOf(i)).start();
        }
    }

    public static void testMap() {
        //Map<String, Object> map = new HashMap<>(); // 线程不安全
        //Map<String, Object> map = Collections.synchronizedMap(new HashMap<>()); // 线程安全，但效率低
        Map<String, Object> map = new ConcurrentHashMap<>();
        for (int i = 1; i <= 40; i++) {
            new Thread(() -> {
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 6));
                System.out.println(map);
            }, String.valueOf(i)).start();
        }
    }
}
